package com.qf.contorller;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.UserServiceImpl;
import com.qf.util.StrUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Struct;

/**
 * @author LiXuekai on 2022/5/27
 */
@WebServlet("/user")
public class UserController extends BaseServlet {
    public String login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //处理乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //1.获取前端传入的参数
        String unameStr = request.getParameter("uname");
        String pwdStr = request.getParameter("pwd");
        //2.判断用户名密码 验证码不为空如果为空重定向到登录界面
        if (!StrUtils.empty(unameStr) || !StrUtils.empty(pwdStr)) {

            response.sendRedirect("login");
        }
        //调用service校验用户名密码是否正确  不正确重定向到登录界面
        UserService userService = new UserServiceImpl();
        User user = userService.login(unameStr, pwdStr);
        //判断用户名密码是否正确
        if (user != null) {
            request.setAttribute("uname", unameStr);
            request.setAttribute("pwd", pwdStr);
            //跳转到登录界面
            return "forward:test.html";

        }


        return null;
    }

    //用户注册
    public String register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置页面的编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取前端传入的参数
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        //判断用户名密码是否为空  如果为空重定向到登录界面
        if (!StrUtils.empty(uname) || !StrUtils.empty(pwd)) {
            response.sendRedirect("register");
        }
        //调用Servlet校验用户名是否存在  如果存在提示用户 不能注册
        UserService userService = new UserServiceImpl();
        boolean chace = userService.chace(uname);
        User user = new User(null, uname, 2, 1);
        if (chace) {
            //结果为true  说明该用户不存在 可以注册
            userService.addUser(user);
        } else {
            //.调用servlet进行添加用户
            return "forward:test1.html";
        }


        return null;
    }

}